package org.rqb.frame;

import com.github.kwhat.jnativehook.GlobalScreen;
import com.github.kwhat.jnativehook.NativeHookException;
import lombok.extern.slf4j.Slf4j;
import org.rqb.Constant;
import org.rqb.config.MyConfig;
import org.rqb.listener.GlobalKeyListener;
import org.rqb.panel.*;
import org.rqb.panel.partPanel.TitlePanel;
import org.rqb.socket.MySocket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Properties;

@Slf4j
public class MyFrame extends JFrame {

    private RepeatPanel repeatPanel;
    private SignPanel signPanel;
    private Properties config = MyConfig.getConfig();
    private QueryLANDevicesPanel queryLANDevicesPanel;
    private ConnectLANDevicesPanel connectLANDevicesPanel;

    private final MySocket mySocket = MySocket.getInstance();
    private ProxyPointPanel proxyPointPanel;
    private M3u8Panel m3u8Panel;
    private MenuPanel menuPanel;
    private ClickFrequencyPanel clickFrequencyPanel;

    public MyFrame() throws HeadlessException {
        windowsInit();

        systemTrayInit();

        layoutInit();

        startListener();


        log.info("项目启动成功");
    }



    private void startListener() {

        try {
            GlobalScreen.registerNativeHook();
            GlobalScreen.addNativeKeyListener(new GlobalKeyListener(this,repeatPanel,clickFrequencyPanel));


        } catch (NativeHookException e) {
            log.warn("全局键盘监听器启动失败");
            throw new RuntimeException(e);
        }


    }

    private void layoutInit() {
        // 创建 JPanel，并设置 CardLayout 布局
        JPanel cardPanel = new JPanel();
        CardLayout cardLayout = new CardLayout();
        cardPanel.setLayout(cardLayout);

        menuPanel = new MenuPanel(cardPanel, cardLayout,this);

        repeatPanel = new RepeatPanel(cardPanel,cardLayout,this);
        signPanel = new SignPanel(cardPanel,cardLayout,this);
        queryLANDevicesPanel = new QueryLANDevicesPanel(cardPanel, cardLayout);
        connectLANDevicesPanel = new ConnectLANDevicesPanel(cardPanel, cardLayout);
        //将查询ip按钮界面告诉MySocket，方便后续将接收的消息传递
        mySocket.addQueryLanDevicesPanel(queryLANDevicesPanel);
        proxyPointPanel = new ProxyPointPanel(cardPanel, cardLayout);

        m3u8Panel = new M3u8Panel();

        clickFrequencyPanel = new ClickFrequencyPanel(cardPanel, cardLayout, this);

        cardPanel.add(menuPanel, "menuPanel");
        cardPanel.add(repeatPanel, "repeatPanel");
        cardPanel.add(signPanel, "signPanel");
        cardPanel.add(queryLANDevicesPanel, "queryLANDevicesPanel");
        cardPanel.add(connectLANDevicesPanel, "connectLANDevicesPanel");
        cardPanel.add(proxyPointPanel, "proxyPointPanel");
        cardPanel.add(m3u8Panel, "m3u8Panel");
        cardPanel.add(clickFrequencyPanel,"clickFrequencyPanel");


        this.getContentPane().add(cardPanel, BorderLayout.CENTER);


        this.getContentPane().add(new TitlePanel(this,cardPanel,cardLayout,repeatPanel), BorderLayout.NORTH);

    }

    private void systemTrayInit() {
        // 检查系统是否支持托盘
        if (!SystemTray.isSupported()) {
            System.out.println("系统托盘不支持");
            return;
        }
        PopupMenu popupMenu = new PopupMenu("菜单");

        MenuItem restoreItem  = new MenuItem("show");
        restoreItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MyFrame.this.displayAtTheForefront();

            }
        });
        MenuItem exitItem = new MenuItem("exit");
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        //将菜单选项假如托盘
        popupMenu.add(restoreItem);
        popupMenu.add(exitItem);

        //获取系统托盘图标
        Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icon.ico"));
        TrayIcon trayIcon = new TrayIcon(image, "weToolBox", popupMenu); //设置托盘图标
        trayIcon.setImageAutoSize(true);

        //设置任务栏图标
        this.setIconImage(image);

//        trayIcon.displayMessage("1","2",TrayIcon.MessageType.INFO);

        // 双击系统托盘图标还原窗口
        trayIcon.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MyFrame.this.displayAtTheForefront();
            }
        });


        try {
            SystemTray systemTray = SystemTray.getSystemTray();
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            e.printStackTrace();
        }



        // 设置 JFrame 最小化时隐藏，并显示系统托盘图标
        // 这个是用来将最小化的窗口不显示
//        this.addWindowStateListener(new WindowStateListener() {
//            @Override
//            public void windowStateChanged(WindowEvent e) {
//                if (e.getNewState() == Frame.ICONIFIED) {
//                    MyFrame.this.setVisible(false);
//                }
//            }
//        });





    }

    private void windowsInit() {
        this.setTitle("weToolBox");
        if ("true".equals(config.getProperty(Constant.CONFIG_HIED_ONEXIT_FIELD))) {
            this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        } else {
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        this.setSize(Constant.FRAME_WIDTH, Constant.FRAME_HEIGHT);
        this.setLocationRelativeTo(null);



    }

    public void displayAtTheForefront(){
//        this.setState(Frame.NORMAL);  // 将状态设置为正常
//        this.setVisible(true);        // 确保窗口可见
//        this.toFront();               // 将窗口置于最前方
//        this.requestFocus();          // 请求焦点

        // 恢复最小化的窗口状态
        if (this.getExtendedState() == Frame.ICONIFIED) {
            this.setExtendedState(Frame.NORMAL);  // 解除最小化
        }

        this.setVisible(true);  // 确保窗口可见

        // 使用延迟调用确保窗口获得焦点并置于最前
        java.awt.EventQueue.invokeLater(() -> {
            this.toFront();  // 将窗口置于最前
            this.requestFocus();  // 请求焦点
        });

    }



}
